/**
 * 
 */
package de.tum.in.eist.poll.client.views.widgets;

import java.util.HashMap;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ListBox;

import de.tum.in.eist.poll.client.DelayedAction;
import de.tum.in.eist.poll.client.controllers.Controller;
import de.tum.in.eist.poll.shared.beans.Lecture;

/**
 * A widget, which allows a selection of the lectures
 * for example as a dropdownbox
 * @author Sebastian Hofstetter
 *
 */
public class LecturesSelectWidget extends Composite{
	private ListBox lectureBox = new ListBox();
	private HashMap<String, Integer> items = new HashMap<String, Integer>();
	
	public LecturesSelectWidget() {
		Lecture[] lectures = Controller.controller.getLectures();
		
		// adds an item for each lecture into the dropdownbox
		for (int i = 0; i< lectures.length; i++) {
			lectureBox.addItem(lectures[i].getLectureTitle(), lectures[i].getLectureID());
			items.put(lectures[i].getLectureID(), i);
		}
		
		lectureBox.setVisibleItemCount(1); // sets the listbox to a dropdownbox
		lectureBox.addStyleName("lecturesSelect");
		lectureBox.addChangeHandler(new ChangeHandler() {
			
			@Override
			public void onChange(ChangeEvent event) {
				Controller.controller.setCurrentLectureId(lectureBox.getValue(lectureBox.getSelectedIndex()), new DelayedAction(){
					@Override
					// refreshes the page on lecture change
					public void run() {
						Controller.controller.refreshPage();
					}
				});
			}
		});
		
		// restores the correct selected item after the page changes
		if (Controller.controller.getCurrentLectureId() != null) {
			lectureBox.setSelectedIndex(items.get(Controller.controller.getCurrentLectureId()));
		}
		
		initWidget(lectureBox);
	}
}
